package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = MenuService.class)
@Transactional

public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        List<Menu> menuList = new ArrayList<>();

        if (queryString == null) {
            menuList = menuDao.getMenuLevelIsOne();

        } else {
            menuList = menuDao.getMenuLevelIsOneByQueryString(queryString);
        }
        for (Menu menu1 : menuList) {
            List<Menu> children = menuDao.getByParentMenuIdMenuLevelIsTwo(menu1.getId());
            menu1.setChildren(children);
        }

        PageInfo pageInfo = new PageInfo(menuList);
        return new PageResult(pageInfo.getTotal(), menuList);
    }

    @Override
    public Result add(Map map) {
        try {
            menuDao.insertMenu(map);
            return new Result(true, "增加菜单成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "增加失败");
        }
    }

    @Override
    public Result findById(Integer menuId) {
        try {
            Map map = menuDao.findById(menuId);
            return new Result(true, "查询菜单详细信息成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询菜单详细信息失败");
        }

    }

    @Override
    public Result edit(Map map) {
        try {
            menuDao.updateMenu(map);
            return new Result(true, "修改数据成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改数据失败");
        }

    }

    @Override
    public Result delete(Integer menuId) {
        try {
            menuDao.deleteMenu(menuId);
            return new Result(true, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "删除失败");
        }
    }
}
